import uvicorn as uvicorn
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.sessions import SessionMiddleware
from starlette.requests import Request
from starlette.types import ASGIApp, Receive, Scope, Send

class MutilAMiddleware(BaseHTTPMiddleware):
    def __init__(self, app, assigned_number):
        super().__init__(app)
        self.app = app
        self.assigned_number = assigned_number

    # async def dispatch(self, request: Request, call_next):
    #     print(f"{self.assigned_number}:'A' middleware executed!")
    #     response = await call_next(request)
    #     return response

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] != "http":  # 非http协议
            print('no http executed!')
            await self.app(scope, receive, send)
            return

        print('http executed!')
        req = Request(scope, receive, send)
        if not req.session.get("session_my"):
            req.session.setdefault("session_my", 'abc123')

        await self.app(scope, receive, send)

class MutilBMiddleware(BaseHTTPMiddleware):
    def __init__(self, app, assigned_number):
        super().__init__(app)
        self.assigned_number = assigned_number

    async def dispatch(self, request: Request, call_next):
        print(f"{self.assigned_number}:'B' middleware executed!")
        response = await call_next(request)
        return response


app = FastAPI()

app.add_middleware(MutilAMiddleware, assigned_number=1)
app.add_middleware(MutilBMiddleware, assigned_number=2)
# 提供了基于cookie的HTTP会话session_cookie管理功能。
app.add_middleware(
    SessionMiddleware,
    secret_key="sa1de2hew3agb4wft34ba",
    session_cookie="session_id",
    max_age=14 * 24 * 60 * 60,
)


@app.get("/")
async def index():
    print("'index' router executed!")
    return "test middleware"


if __name__ == "__main__":
    uvicorn.run(app="test:app", port=8000, reload=True)
